package com.jeff.game.tools.level;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

/**
 * Contains the blocks that will make up a background.
 */
public class BlockFile
{
  private final String filename;
  private final int blockRows;
  private final int blockCols;

  /**
   * @param filename Block file name
   * @param blockRows Number of rows in file
   * @param blockCols Number of columns in file
   * @return 2D array of characters
   * @throws IOException
   */
  public BlockFile(String filename, int blockRows, int blockCols)
  {
    this.filename = filename;
    this.blockRows = blockRows;
    this.blockCols = blockCols;
  }

  /**
   * Reads the block file into a 2D character array
   * @return 2D char array of blocks
   * @throws IOException
   */
  public char[][] toBlocks() throws IOException
  {
    char[][] blocks = new char[blockRows][blockCols];
    BufferedReader reader = null;

    try
    {
      reader = new BufferedReader(new FileReader(filename));
      String line = "";
      int i = 0;

      while ((line = reader.readLine()) != null)
      {
        blocks[i] = line.toCharArray();
        i++;
      }
    }
    finally
    {
      if (reader != null) reader.close();
    }

    return blocks;
  }
}
